import Cookie from 'js-cookie'
export default {
    state: {
        isCollapse: false,  // 控制侧边栏展开收起
        defaultActive: '/',
        tabsList: [  // 面包屑数据
            {
                path: '/home',
                name: 'home',
                label: '首页',
                icon: 'home'
            }
        ],
        currentMenu: null, // 高亮的面包屑
        menu: []
    },
    mutations: {
        collapseMenu(state){
            state.isCollapse = !state.isCollapse;
        },
        isDefaultActive(state,val){
            state.defaultActive = val.path;
        },
        addTabsList(state,val){
            state.tabsList.push(val)
            state.currentMenu = val
        },
        selectMenu(state,val){
            if(val.name !== 'home'){
                state.currentMenu = val
                console.log(val);
                const result = state.tabsList.findIndex(item => item.name === val.name)
                if(result === -1){
                    state.tabsList.push(val)
                }
            }else{
                state.currentMenu = null
            }
        },
        closeTag(state, val){
            const result = state.tabsList.findIndex(item => item.name === val.name)
            state.tabsList.splice(result,1);
        },
        setMenu(state, val){
            state.menu = val;
            Cookie.set('menu', JSON.stringify(val))
        },
        clearMenu(state){
            state.menu = []
            Cookie.remove('menu')
        },
        addMenu(state,router){
            if(!Cookie.get('menu')){
                return
            }
            const menu = JSON.parse(Cookie.get('menu'))
            state.menu = menu
            // 动态添加路由
            const menuArray = []
            menu.forEach(item => {
                if(item.children){
                    item.children = item.children.map(item1 => {
                        item1.component = () => import(`../views/${item1.url}`)
                        return item1
                    })
                    menuArray.push(...item.children) // 数组扁平化
                }else{
                    item.component = () => import(`../views/${item.url}`)
                    menuArray.push(item)
                }
            });
            // 路由的动态添加
            // menuArray.forEach(item => {
            //     router.addRoute('Main', item)
            // })
            let menuData = [
                {
                    path: '/',
                    name: 'Main',
                    component: () => import('../views/Main.vue'),
                    redirect: '/home',
                    children: []
                }
            ]
            menuData[0].children = menuArray;
            router.addRoutes(menuData)
        }
    }
}